#include <stdio.h>

void histeq(int * arr, int col, int row)
{
    int * arr_ = arr;

    // 初始化像素点个数数组
    int pixel_num[256];
    for (int i = 0; i < 256; ++i) {
        pixel_num[i] = 0;
    }

    // 统计像素点个数
    int pixel_total_num = col * row;
    for (int i = 0; i < col; ++i) {
        for (int j = 0; j < row; ++j) {
            pixel_num[arr[j]] ++;
        }
        arr += row;
    }
    arr = arr_;

    // 得到变换后的灰度级
    int pixel_transform[256];
    double pixel_freq = 0;
    for (int i = 0; i < 256; ++i) {
        pixel_freq += (double )pixel_num[i]/pixel_total_num;
        pixel_transform[i] = (int)(pixel_freq*255+0.5);
    }

    // 变换灰度级
    for (int i = 0; i < col; ++i) {
        for (int j = 0; j < row; ++j) {
            arr[j] = pixel_transform[arr[j]];
        }
        arr += row;
    }
}

int main() {
    int test_matrix[8][8] = {
            1,5,255,225,100,200,255,200,
            1,7,254,255,100,10,10,9,
            3,7,10,100,100,2,9,6,
            3,6,10,10,9,2,8,2,
            2,1,8,8,9,3,4,2,
            1,0,7,8,8,3,2,1,
            1,1,8,8,7,2,2,1,
            2,3,9,8,7,2,2,0
    };

    histeq((int *)test_matrix, 8, 8);
    
    for (int i = 0; i < 8; ++i) {
        for (int j = 0; j < 8; ++j) {
            printf("%3d ", test_matrix[i][j]);
        }
        printf("\n");
    }

    getchar();
    return 0;
}
